const { sequelize } = require('../config/db');
const { User, Favorite } = require('./User');
const AIRole = require('./AIRole');
const Interaction = require('./Interaction');
const SharedImage = require('./SharedImage');
const UserLike = require('./UserLike');
const ApiKey = require('./ApiKey');

// 定义模型之间的关系
// 用户与交互记录是一对多关系
User.hasMany(Interaction, { foreignKey: 'user_id' });
Interaction.belongsTo(User, { foreignKey: 'user_id' });

// AI角色与交互记录是一对多关系
AIRole.hasMany(Interaction, { foreignKey: 'ai_role_id' });
Interaction.belongsTo(AIRole, { foreignKey: 'ai_role_id' });

// 用户与AI角色是多对多关系（通过收藏表）
User.belongsToMany(AIRole, { through: Favorite, foreignKey: 'user_id' });
AIRole.belongsToMany(User, { through: Favorite, foreignKey: 'ai_role_id' });

// 添加直接关联，解决EagerLoading问题
Favorite.belongsTo(AIRole, { foreignKey: 'ai_role_id' });
Favorite.belongsTo(User, { foreignKey: 'user_id' });

// 用户与分享图片是一对多关系
User.hasMany(SharedImage, { foreignKey: 'user_id' });
SharedImage.belongsTo(User, { foreignKey: 'user_id' });

// AI角色与分享图片是一对多关系（可选）
AIRole.hasMany(SharedImage, { foreignKey: 'ai_role_id' });
SharedImage.belongsTo(AIRole, { foreignKey: 'ai_role_id' });

// 用户点赞关系
User.belongsToMany(SharedImage, {
  through: UserLike,
  foreignKey: 'user_id',
  as: 'LikedImages'
});
SharedImage.belongsToMany(User, {
  through: UserLike,
  foreignKey: 'shared_image_id',
  as: 'LikedByUsers'
});

// UserLike与SharedImage和User的直接关联
UserLike.belongsTo(SharedImage, { foreignKey: 'shared_image_id' });
SharedImage.hasMany(UserLike, { foreignKey: 'shared_image_id' });
UserLike.belongsTo(User, { foreignKey: 'user_id' });
User.hasMany(UserLike, { foreignKey: 'user_id' });

// API密钥与用户的关系（创建者）
User.hasMany(ApiKey, { foreignKey: 'created_by' });
ApiKey.belongsTo(User, { foreignKey: 'created_by' });

// 初始化数据库
const initDB = async () => {
  try {
    // 使用 force: false 避免重复创建索引
    // 如果需要更新表结构，请使用 Sequelize 迁移
    await sequelize.sync({ force: false });
    console.log('数据库表同步成功');
  } catch (error) {
    console.error('数据库表同步失败:', error);
    throw error;
  }
};

module.exports = {
  User,
  AIRole,
  Interaction,
  Favorite,
  SharedImage,
  UserLike,
  ApiKey,
  initDB
};